package com.taikang.hmp.hbusiness.diabetes.measure.sport.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.service.impl.BaseServiceImpl;
import com.taikang.hmp.frame.customer.bean.CustomerInfo;
import com.taikang.hmp.hbusiness.diabetes.measure.sport.bean.Sport;
import com.taikang.hmp.hbusiness.diabetes.measure.sport.bean.SportDetail;
import com.taikang.hmp.hbusiness.diabetes.measure.sport.service.ISportService;
import com.taikang.hmp.hbusiness.diabetes.measure.sport.service.SportUtil;

/**
 * 运动 author:qrp time:2015年8月5日 上午11:10:22
 */
public class SportServiceImpl extends BaseServiceImpl implements ISportService {

	private static Logger logger = LoggerFactory.getLogger(SportServiceImpl.class);
	
	public String saveSport(Dto paramDto) {
		String uid = paramDto.getAsString("uid");// 客户ID
		String    customerid = paramDto.getAsString("customerid");
		List<Dto> sportList  = paramDto.getAsList("sportlist");
		if(sportList!=null && !sportList.isEmpty()){
			Map<String, String> map = new HashMap<String, String>();
			map.put("customerid", customerid);
			
			//通过uid和date删除这个时间的所有数据
			Dto detailobj1   = sportList.get(0);
			String end_date1 = detailobj1.getAsString("enddate");
			map.put("date", end_date1.substring(0, 10));
			super.getNewDao().delete("sport_space.delete_sport", map);
			super.getNewDao().delete("sport_space.delete_sportDetail", map);
			
			//插入新的数据
			for (int i = 0; i < sportList.size(); i++) {
				Dto detailobj = sportList.get(i);
				String start_date = detailobj.getAsString("startdate");// 开始时间（yyyy-mm-dd 22:00）(可为空)
				String end_date = detailobj.getAsString("enddate");// 结束时间（yyyy-mm-dd 22:00）
				String sport_type_cd = detailobj.getAsString("sporttypecd");// 运动类别（散步、游泳等）
				String value = detailobj.getAsString("value");// 运动时间（分钟）
				String step_num = detailobj.getAsString("stepnum");// 步数（可为空）
				// 主表信息
				Sport sport = new Sport();
				sport.setDate(end_date);// 将结束时间作为执行时间
				sport.setCustomer_id(customerid);
				sport.setSporttype_cd(sport_type_cd);
				sport.setStepnum(step_num);
				String record_id = java.util.UUID.randomUUID().toString();
				sport.setRecord_id(record_id);
				Date operate_date = new Date();
				sport.setOperate_date(operate_date);
				sport.setSource_cd(paramDto.getAsString("requestsource"));
				sport.setOperater(uid);
				try {
					super.getNewDao().insert("sport_space.insert_sport", sport);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 明细
				SportDetail detail = new SportDetail();
				detail.setRecord_id(java.util.UUID.randomUUID().toString());
				detail.setSport_id(record_id);
				detail.setStartdate(start_date);
				detail.setEnddate(end_date);
				detail.setValue(value);
				detail.setStepnum(step_num);
				detail.setOperate_date(operate_date);
				detail.setSource_cd(paramDto.getAsString("requestsource"));
				detail.setOperater(uid);
				try {
					super.getNewDao().insert("sport_space.insert_sportDetail", detail);
				} catch (Exception e) {
					logger.error(e.getMessage(),e);
					e.printStackTrace();
				}
			}
		}else{
			logger.error("sportlist is null");
		}
		// 评判结果
		String sportWords = null;
		return sportWords;
	}

	public List<Object> getSportList(JSONObject jsonObj) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("uid", jsonObj.getString("uid"));
		map.put("start_date", jsonObj.getString("start_date") + "00:00");
		map.put("end_date", jsonObj.getString("end_date") + "23:59");
		List<Sport> info = super.getNewDao().queryForList("sport_space.getSport", map);
		List<Object> resultList = new ArrayList<Object>();
		for (int i = 0; i < info.size(); i++) {
			JSONObject result = new JSONObject();
			result.put("date", info.get(i).getDate());// 执行日期
			result.put("sportTypeCd", info.get(i).getSporttype_cd());// 运动类别
			result.put("calorie", info.get(i).getCalorie());// 消耗卡路里
			result.put("stepNum", info.get(i).getStepnum());// 步数当量
			// 拼接运动列表
			List<SportDetail> info1 = super.getNewDao().queryForList(
					"sport_space.getSportDetail", info.get(0).getRecord_id());
			for (int j = 0; j < info1.size(); j++) {
				JSONObject mealList = new JSONObject();
				mealList.put("sportId", info1.get(j).getSport_id());// 运动编码
				mealList.put("startDate", info1.get(j).getValue());// 开始时间
				mealList.put("endDate", info1.get(j).getEnddate());// 结束时间
				mealList.put("sportTypeCd", info1.get(j));// 运动类别
				mealList.put("value", info1.get(j).getValue());// 时间
				mealList.put("calorie", info1.get(j).getCalorie());// 热量
				mealList.put("stepNum", info1.get(j).getStepnum());// 当量步数
				result.put("mealList", mealList);
			}
			resultList.add(result);
		}
		return resultList;
	}

	public List<Object> getDaySportList(JSONObject jsonObj) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("uid", jsonObj.getString("uid"));
		map.put("start_date", jsonObj.getString("start_date") + "00:00");
		map.put("end_date", jsonObj.getString("end_date") + "23:59");
		List<Sport> info = super.getNewDao().queryForList("sport_space.getSport", map);
		List<Object> resultList = new ArrayList<Object>();
		for (int i = 0; i < info.size(); i++) {
			JSONObject result = new JSONObject();
			result.put("date", info.get(i).getDate());// 执行日期
			result.put("sportTypeCd", info.get(i).getSporttype_cd());// 运动类别
			result.put("calorie", info.get(i).getCalorie());// 消耗卡路里
			result.put("stepNum", info.get(i).getStepnum());// 步数当量
			result.put("directMsg", "");// 合理性评价
			// 拼接运动列表
			List<SportDetail> info1 = super.getNewDao().queryForList(
					"sport_space.getSportDetail", info.get(0).getRecord_id());
			for (int j = 0; j < info1.size(); j++) {
				JSONObject mealList = new JSONObject();
				mealList.put("sportId", info1.get(j).getSport_id());// 运动编码
				mealList.put("startDate", info1.get(j).getValue());// 开始时间
				mealList.put("endDate", info1.get(j).getEnddate());// 结束时间
				mealList.put("sportTypeCd", info1.get(j));// 运动类别
				mealList.put("value", info1.get(j).getValue());// 时间
				mealList.put("calorie", info1.get(j).getCalorie());// 热量
				mealList.put("stepNum", info1.get(j).getStepnum());// 当量步数
				result.put("mealList", mealList);
			}
			resultList.add(result);
		}
		return resultList;
	}

	@Override
	public List<Sport> getSportChartList(Dto paramDto) {
		
		Sport sport = new Sport();
		sport.setCustomer_id(paramDto.getAsString("customerid"));
		if ("1".equals(paramDto.getAsString("day"))) {
			sport.setDates(paramDto.getAsString("date"));
		} else {
			sport.setBef_date(paramDto.getAsString("befdate") + " 00:00");
			sport.setAft_date(paramDto.getAsString("aftdate") + " 23:59");
		}
		List<Sport> result = new ArrayList<Sport>();
		List<Dto> list = super.getNewDao().queryForList("sport_space.getSportChartList", sport);
		if(list!=null && list.size()>0){
			for(int i=0;i<list.size();i++){
				Sport sportResult = new Sport();
			Dto dtoResult = list.get(i);
			sportResult.setStepnum(dtoResult.getAsString("stepnum"));
			sportResult.setCalorie(dtoResult.getAsString("calorie"));
			sportResult.setDates(dtoResult.getAsString("dates"));
			result.add(sportResult);
			}
		}
		return result;
	}

	@Override
	public List<Sport> getSportRecordList(Dto paramDto) {
	
		List<Sport> sportList = new ArrayList<Sport>();
		Sport sport = new Sport();
		sport.setCustomer_id(paramDto.getAsString("customerid"));


		for (int i = 6; i >= 0; i--) {
			try {
				sport.setDates(SportUtil.getFormerDate(new Date(), i + 1));
				Sport sportResult = new Sport();
				List<Dto> list = super.getNewDao().queryForList("sport_space.getSportChartList", sport);
				if(list!=null && list.size()>0){
					Dto dtoResult = list.get(0);
				sportResult.setStepnum(dtoResult.getAsString("stepnum"));
				sportResult.setCalorie(dtoResult.getAsString("calorie"));
				sportResult.setDates(dtoResult.getAsString("dates"));
				}
				sportList.add(sportResult);
			} catch (ParseException e) {				
				e.printStackTrace();
			}
		}
		
		return sportList;
	}

	@Override
	public List<Sport> getSportTableList(Dto dto) {
		
		logger.info("uid: "+dto.getAsString("uid"));
		String uid = dto.getAsString("uid");
		List<CustomerInfo> customer = super.getNewDao().queryForList("user_space.getCustomer_uid", uid);
		double weight = 0;
		if (customer.size() > 0) {
			weight = Double.parseDouble(customer.get(0).getWeight());
		}
		Sport sport = new Sport();
		
		logger.info("customerid: "+dto.getAsString("customerid"));
		sport.setCustomer_id(dto.getAsString("customerid"));
		
		logger.info("day: "+dto.getAsString("day"));
		if ("1".equals(dto.getAsString("day"))) {
			logger.info("date: "+dto.getAsString("date"));
			sport.setDates(dto.getAsString("date"));
		} else {
			logger.info("befdate: "+dto.getAsString("befdate"));
			sport.setBef_date(dto.getAsString("befdate") + " 00:00");
			logger.info("aftdate: "+dto.getAsString("aftdate"));
			sport.setAft_date(dto.getAsString("aftdate") + " 23:59");
		}
		List<Sport> resultList = new ArrayList<Sport>();
		List<Sport> sportList = super.getNewDao().queryForList(
				"sport_space.getSportTableList", sport);
		if (!(sportList.size() > 0)) {
			return null;
		} else {
			Sport sportResult = new Sport();
			for (int i = 0; i < sportList.size(); i++) {
				boolean flag = false;
				if (i > 0) {
					flag = sportList
							.get(i)
							.getDates()
							.substring(0, 10)
							.equals(sportList.get(i - 1).getDates()
									.substring(0, 10));
					if (!flag) {
						resultList.add(sportResult);
						sportResult = new Sport();
					}
				}
				sportResult.setDates(sportList.get(i).getDates()
						.substring(0, 10));
				if (!flag) {
					sportResult.setStepnum(sportList.get(i).getStepnum());
				} else {
					int Stepnum = SportUtil.changeString(sportList.get(i)
							.getStepnum())
							+ SportUtil.changeString(sportResult.getStepnum());
					sportResult.setStepnum(String.valueOf(Stepnum));
				}
				if ("0".equals(sportList.get(i).getSporttype_cd())) {
					// 强度
					int intensity = Integer.parseInt(sportList.get(i)
							.getStepnum()) / 15;
					// 系数
					double ratio = SportUtil.getRatio(intensity);
					if (!flag) {
						sportResult.setCalorie(String.valueOf(Math.round(ratio
								* weight * 15)));
					} else {
						double calorie = Math.round((ratio * weight * 15)
								+ SportUtil.changeStringD(sportResult
										.getCalorie()));
						sportResult.setCalorie(String.valueOf(calorie));
					}

				} else {
					double otherRatio = 0.0525;
					SportDetail sportDetail = (SportDetail)super.getNewDao().queryForObject(
							"sport_space.getSportTime", sportList.get(i));
					if (!flag) {
						sportResult.setCalorie(String.valueOf(Math
								.round(otherRatio
										* weight
										* Double.parseDouble(sportDetail
												.getValue()))));
					} else {

						sportResult.setCalorie(String.valueOf(Math
								.round(otherRatio
										* weight
										* Double.parseDouble(sportDetail
												.getValue()))
								+ SportUtil.changeStringD(sportResult
										.getCalorie())));
					}
				}
				if (i == sportList.size() - 1) {
					resultList.add(sportResult);
				}

			}

		}
		return resultList;
	}

	/**
	 * 根据UId取目标步数
	 * 
	 * @param jsonObj
	 * @return
	 */
	public int getTarget(JSONObject jsonObj) {
		String uid = jsonObj.getString("uid");
		List<CustomerInfo> customer = super.getNewDao().queryForList(
				"user_space.getCustomer_uid", uid);
		double bmi = 0;
		if (customer.size() > 0) {
			bmi = Math
					.round(Double.parseDouble(customer.get(0).getWeight())
							/ Math.pow(Double.parseDouble(customer.get(0)
									.getHeight()) / 100, 2) * 10) / 10.0;
		}
		int stepnum = 0;
		if (bmi < 24) {
			// 运动处方1
			stepnum = 6000;
		} else if (bmi > 24 && bmi < 28) {
			// 运动处方2
			stepnum = 6000;
		} else if (bmi >= 28) {
			// 运动处方3
			stepnum = 6000;
		}
		return stepnum;
	}

}
